package com.yazi.mxz.admin.common;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yazi.mxz.common.MyUtil;
import com.yazi.mxz.common.entity.beans.Admin;
import com.yazi.mxz.common.entity.beans.Role;
import com.yazi.mxz.common.service.AdminService;
import com.yazi.mxz.common.service.RoleService;


/**
 * 
 *	
 *	@author mo_yq5@163.com
 * 	@date 2013-11-22  
 *
 */
public class Realm extends AuthorizingRealm {
	private static Logger log = LoggerFactory.getLogger(Realm.class);
	@Resource 
	AdminService adminService;
	@Resource
	RoleService roleService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		// TODO Auto-generated method stub
		SimpleAuthorizationInfo autho = new SimpleAuthorizationInfo();
		Admin admin = (Admin)principal.getPrimaryPrincipal();
		if (null != admin) {
			List<Role> roles = roleService.listByAdminId(admin.getAdminId());
			for (Role role : roles) {
				autho.addRole("" + role.getRoleId());
				String[] perms = role.getPerms().split(",");
				for (String perm : perms) {
					autho.addStringPermission(perm);
				}
			}
			
		}
		return autho;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		// TODO Auto-generated method stub
		String password = new String((char[])arg0.getCredentials());
		Admin admin = new Admin();
		//admin.setPassword(password);
		admin.setName(String.valueOf(arg0.getPrincipal()));
		List<Admin> list = adminService.list(admin);
		if (list.size() != 1) {
			log.debug("管理员认证未通过：name={}", admin.getName());
			throw new AuthenticationException();
		}
		admin = list.get(0);
		if (!admin.getPassword().equals(MyUtil.encodePwd(password))) {
			log.debug("管理员认证未通过,密码不正确：name={}", admin.getName());
			throw new AuthenticationException();
		}
		log.debug("管理员认证通过：name={}", admin.getName());
		SimpleAuthenticationInfo authe = new SimpleAuthenticationInfo(admin, password, getName());
		return authe;
	}

}
